#pragma once
#include <atomic>
#include <mutex>
#include<vector>
#include<functional>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <memory>
#include "CurrentThread.h"
#include "nocopy.h"
#include"TimeStamp.h"
#include"Poller.h"
// #pragma once

// #include <functional>
// #include <vector>
// #include <atomic>
// #include <memory>
// #include <mutex>

// #include "nocopy.h"
// #include "TimeStamp.h"
// #include "CurrentThread.h"

class Channel;
class Poller;


class EventLoop : nocopyable
{
public:
    using Functor = std::function<void()>;
    EventLoop() ;

    ~EventLoop();
   

    void loop();
    
    void quit();
   
    TimeStamp pollReturnTime() const { return pollReturnTime_; }
    // 在当前loop中执行cb
    void runInLoop(Functor cb);
  
    // 把cb放入队列中，唤醒loop所在的线程，执行cb
    void queueInLoop(Functor cb);
 

    // 唤醒loop所在的线程
    void wakeup();
   
    // poller中的方法
    void updateChannel(Channel *channel);
   
    void removeChannel(Channel *channel);
   
    bool hasChannel(Channel *channel);
   
    // 判断loop对象是否在当前线程
    bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); }

private:
    void handleRead();
    // 唤醒
    void doPendingFunctors();
   // 执行函数列表回调
    using ChanneList = std::vector<Channel *>;

    std::atomic_bool looping_;
    std::atomic_bool quit_; // 原子操作
    std::atomic_bool callingPendingFunctions_;
    const pid_t threadId_; // 记录当前线程id
    TimeStamp pollReturnTime_;

    std::unique_ptr<Poller> poller_;
    int wakeup_; // 当loop获取到一个新用户的channel使用轮询唤醒一个subloop处理channel
    std::unique_ptr<Channel> wakeupChannel_;
    Poller::ChannelList activeChannels_;
    std::vector<Functor> pendingFunctors_;
    std::mutex mutex_; // 互斥锁，同步pending的多线程操作
};